<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <!--           表格修改-->
            <div class="gd-item" v-for="(item, index) in state.tableData" :key="item.projectId">
                <div class="target-table">
                    <a-table
                        :columns="formatColumns(item.columnList)"
                        :data-source="groupListData(item.dataSourceList)"
                        bordered
                        :scroll="{ x: 'max-content' }"
                        :pagination="false"
                        @resizeColumn="handleResizeColumn"
                    >
                        <template #headerCell="{ title, column }">
                            <template v-if="title !== '操作' && title !== '子目标' && title !== '关键路径任务'">
                                <div class="week-title">
                                    {{ title }}
                                </div>
                            </template></template
                        >
                        <template #bodyCell="{ column, record, text }">
                            <!-- 展开/折叠按钮 -->
                            <template v-if="column.dataIndex === 'opration'">
                                <a-button type="link" @click="toggleExpand(record)">
                                    {{ record.expanded ? '折叠' : '展开' }}
                                </a-button>
                            </template>
                            <template
                                v-if="
                                    ![
                                        '子目标',
                                        '关键路径任务',
                                        '任务状态',
                                        '任务备注',

                                    ].includes(column.title)
                                "
                            >
                                <div class="color-div" v-if="text">
                                    <div
                                        class="div-item"
                                        :style="{
                                            backgroundColor: text.plan ? '#FFE58F' : '#fff'
                                        }"
                                    ></div>
                                    <div class="line-table" v-if="text.today"></div>
                                    <div
                                        class="div-item"
                                        :style="{
                                            backgroundColor: getColor(text.actual)
                                        }"
                                    >
                                    </div>
                                </div>
                                <div v-else class="color-div">
                                    <div class="div-item"></div>
                                    <div class="line-table" v-if="column.today"></div>
                                    <div class="div-item"> </div>
                                </div>
                            </template>
                            <!-- 其他列的内容 -->
                            <template v-else>
                                <a-tooltip>
                                    <template #title>双击编辑</template>
                                    <div
                                        v-html="formatText(text)"
                                        :style="{
                                            width: '100%',
                                            height: record.expanded ? 'auto' : '20px',
                                            overflow: 'hidden',
                                            whiteSpace: 'normal',
                                            textOverflow: 'ellipsis',
                                            textAlign: column.dataIndex === 'goalsNameIndex' ? 'center' : 'left',
                                            cursor: ['关键路径任务', '子目标'].includes(column.title)
                                                ? 'auto'
                                                : 'pointer',
                                            fontWeight: column.title === '子目标' ? '600' : '400'
                                        }"
                                        @dblclick="showChangeWeek(column, record, item.projectId)"
                                    >
                                    </div>
                                </a-tooltip>
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
            <!--           表格修改-->
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'message': {
            type: [String],
            default: ''
        },
        'projectId': {
            type: [String, Number],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
        'abc': undefined,
        'def': undefined
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)

    const pageParams = [
        { 'name': 'abc', 'dataType': 'STRING' },
        { 'name': 'def', 'dataType': 'STRING' }
    ]
    let setPageParams = () => {
        pageParams.forEach(param => {
            strategyMap[param.dataType](param, route.query[param.name])
        })
    }
    const strategyMap = {
        STRING: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            pageParameter_state[param.name] = paramValue
        },
        BOOLEAN: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            if ('true' === (paramValue || '').toLowerCase()) {
                pageParameter_state[param.name] = true
            } else if ('false' === (paramValue || '').toLowerCase()) {
                pageParameter_state[param.name] = false
            } else {
                message.error('参数传入错误！类型不匹配！')
            }
        },
        NUMBER: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            if (!isNaN(paramValue)) {
                pageParameter_state[param.name] = Number(paramValue)
            } else {
                message.error('参数传入错误！类型不匹配！')
            }
        },
        ARRAY: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
                pageParameter_state[param.name] = []
            } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
                try {
                    pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue))
                } catch (error) {
                    console.error('参数解析失败 ', error)
                    message.error('参数解析失败 ', error)
                }
            } else {
                console.error('参数传入错误！类型不匹配！')
                message.error('参数传入错误！类型不匹配！')
            }
        }
    }
    /*** PUBLISH_EXEGESIS ***
 immediateWatch(
 () => route.query,
 () => {
 setPageParams();
 queryUpdateFlag.value++;

 }
 )
 *** PUBLISH_EXEGESIS ***/
    onMounted(() => {
        setPageParams()
    })

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const state = reactive({
        dataSource: []
    })

    const selectedMonth = ref(null) // Store selected month

    // 月份列表映射
    const months = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
    const monthsMap = {
        '1月': 'janGoalsList',
        '2月': 'febGoalsList',
        '3月': 'marGoalsList',
        '4月': 'aprGoalsList',
        '5月': 'mayGoalsList',
        '6月': 'junGoalsList',
        '7月': 'julGoalsList',
        '8月': 'augGoalsList',
        '9月': 'sepGoalsList',
        '10月': 'octGoalsList',
        '11月': 'novGoalsList',
        '12月': 'decGoalsList'
    }

    // 季度映射
    const monthToQuarter = {
        '1': 'Q1',
        '2': 'Q1',
        '3': 'Q1',
        '4': 'Q2',
        '5': 'Q2',
        '6': 'Q2',
        '7': 'Q3',
        '8': 'Q3',
        '9': 'Q3',
        '10': 'Q4',
        '11': 'Q4',
        '12': 'Q4'
    }

    // Get the goals for the selected month
    const getMonthGoals = (month, item) => {
        if (!month) return null
        const monthGoalsKey = monthsMap[month]
        return item[monthGoalsKey] || '暂无目标'
    }

    // Get the goals for the quarter based on the selected month
    const getQuarterGoals = target => {
        if (!target) return null
        return target
    }

    let baseListColumn = ref([
        {
            title: '子目标',
            tilte: '子目标',
            dataIndex: 'goalsNameIndex',
            customCell: ({ goalsNameRowSpan }) => {
                return {
                    rowSpan: goalsNameRowSpan
                }
            }
        }
    ])
    function groupListData(data) {
        if (!data) {
            return
        }
        let currentGoalsNameIndex = ''
        let goalsNameRowSpan = 0

        return data.map((item, index) => {
            // 如果 goalsNameIndex 变化，重置 goalsNameRowSpan，并计算新的 rowSpan
            if (currentGoalsNameIndex !== item.goalsNameIndex) {
                currentGoalsNameIndex = item.goalsNameIndex
                goalsNameRowSpan = 1

                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].goalsNameIndex === item.goalsNameIndex) {
                        goalsNameRowSpan++
                    } else {
                        break
                    }
                }
                item.goalsNameRowSpan = goalsNameRowSpan
            } else {
                item.goalsNameRowSpan = 0
            }
            item.expanded = true
            return item
        })
    }
    function formatColumns(column) {
        let newColumn = [
            ...baseListColumn.value,
            ...column,
            {
                title: '操作',
                fixed: 'right',
                dataIndex: 'opration'
            }
        ]
        return newColumn.map(item => {
            return reactive({
                title: item.tilte,
                ...item,
                align: 'center',
                width: item.title == '操作' ? 100 : 200,
                resizable: item.title == '操作' ? false : true,
                fixed: item.tilte == '子目标' || item.tilte == '关键路径任务' ? 'left' : ''
            })
        })
    }
    function getData(flag) {
        state.tableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/pdtm/goals/v2/search', {
            ...state.searchForm,
            month: selectedMonth.value
        })
            .then(data => {
                if (data.code !== 200) {
                    state.tableData = []
                    state.collapseKey = []
                    message.error(data.message)
                    return
                }
                state.tableData = data.data
                if (flag) {
                    state.collapseKey = [data.data[0].projectId]
                }
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    getData()
    function formatText(text) {
        if (!text) return '--'
        return text.replace(/\n/g, '<br/>')
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .target-table:deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #f5f8ff;
        color: #262626;
        font-weight: 600;
        padding: 8px 0px;
    }

    .target-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        padding: 4px 16px;
        word-break: break-all;
    }
    /*表格修改*/
    /*表格修改*/
</style>
